//
//  Util.m
//  DayPainting
//
//  Created by nian liu on 12-7-28.
//  Copyright (c) 2012年 banma.com. All rights reserved.
//

#import "Util.h"

//#import "SBJsonParser.h"
//#import "SBJsonWriter.h"
#import <QuartzCore/QuartzCore.h>
#import "StringEncryption.h"
#import "GTMBase64.h"

#include <sys/socket.h> 
// Per msqr
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>
#import "BMTipsView.h"

#define SerializeKeyUpdate @"SerializeKeyUpdate"

@interface Util()
+ (UIImage *)image:(UIImage *)image drawInRect:(CGRect)rect;
@end

@implementation Util



#define kDEFAULT_DATE_TIME_FORMAT (@"yyyyMMdd")
//NSDate－>NSString
+ (NSString * )dateToNSNSString:(NSDate * )date{
    NSTimeZone* localzone = [NSTimeZone localTimeZone];
    NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat: kDEFAULT_DATE_TIME_FORMAT];
    [formatter setTimeZone:localzone];
    NSString *dateString = [formatter stringFromDate:date ];
    [formatter release];
    return dateString;
}

// NSString->NSDate
+ (NSDate * )NSStringToDate:(NSString * )string{
    NSTimeZone* GTMzone = [NSTimeZone timeZoneForSecondsFromGMT:0];
    NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat: kDEFAULT_DATE_TIME_FORMAT];
    [formatter setTimeZone:GTMzone];
    NSDate *date = [formatter dateFromString :string ];
    [formatter release];
    return date;
}
//判断某个点是否在某个区域里  
+ (BOOL)isInRect:(CGPoint)p rect:(CGRect)rect
{
    CGFloat rectX = rect.origin.x;
    CGFloat rectY = rect.origin.y;
    CGFloat rectWidth = rect.size.width;
    CGFloat rectHeight = rect.size.height;
    
    CGFloat pX = p.x;
    CGFloat pY = p.y;
    
    if(pX < rectX
       ||(pX > rectX + rectWidth)
       || pY < rectY
       || pY > rectY + rectHeight)
    {
        return FALSE;
    }
    
    return TRUE;
}
#pragma mark - Word Counter
+ (int)countWord:(NSString*)s
{
    int i,n=[s length],l=0,a=0,b=0;
    unichar c;
    for(i=0;i<n;i++){
        c=[s characterAtIndex:i];
        if(isblank(c)){
            b++;
        }else if(isascii(c)){
            a++;
        }else{
            l++;
        }
    }
    if(a==0 && l==0) return 0;
    return l+(int)ceilf((float)(a+b)/2.0);
}

+ (NSString *)stringWithDate:(NSDate *)date{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyyMMdd"];
    NSString *string = [dateFormatter stringFromDate:date];
    [dateFormatter release];
    return string;
}
+ (BOOL)unfoldUpdateTime{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyyMMdd";
    NSString *timeStr =  [dateFormatter stringFromDate:[NSDate date]];
    [dateFormatter release];
    NSString *lastTimeStr = [[NSUserDefaults standardUserDefaults] objectForKey:SerializeKeyUpdate];
    if (lastTimeStr == nil || ![lastTimeStr isEqualToString:timeStr]) {
        [[NSUserDefaults standardUserDefaults] setObject:timeStr forKey:SerializeKeyUpdate];
        [[NSUserDefaults standardUserDefaults] synchronize];
        return YES;
    }
    return NO;
}

/*
#pragma mark - JSON Convert
+ (NSDictionary *)convertJSONToDict:(NSString *)string 
{
    SBJsonParser * parser = [[[SBJsonParser alloc] init] autorelease];
	return [parser objectWithString:string];
}

+ (NSString *)convertDictToJSON:(NSDictionary *)dict 
{
    SBJsonWriter * writer = [[[SBJsonWriter alloc] init] autorelease];
	return [writer stringWithObject:dict];
}
*/
+ (id)getElementForKey:(id)key fromDict:(NSDictionary *)dict
{
    id obj = [dict objectForKey:key];
    if ([obj isKindOfClass:[NSString class]] && [obj isEqual:@""]) {
        return nil; //空字符串
    } else if ([obj isKindOfClass:[NSNull class]]) {
        return nil; //空类
    }  
    return obj;
}

+ (id)getElementForKey:(id)key fromDict:(NSDictionary *)dict forClass:(Class)class
{
    id obj = [dict objectForKey:key];
    if ([obj isKindOfClass:class]) {
        if ([obj isKindOfClass:[NSString class]] && [obj isEqual:@""]) {
            return nil;
        } else {
            return obj;
        }
    }
    return nil;
}

#pragma mark - UTF8 Encode
+ (NSString *)encodeUTF8Str:(NSString *)encodeStr
{  
    CFStringRef nonAlphaNumValidChars = CFSTR("![        DISCUZ_CODE_1        ]’()*+,-./:;=?@_~");          
    NSString *preprocessedString = (NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault, (CFStringRef)encodeStr, CFSTR(""), kCFStringEncodingUTF8);          
    NSString *newStr = [(NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)preprocessedString,NULL,nonAlphaNumValidChars,kCFStringEncodingUTF8) autorelease];  
    [preprocessedString release];  
    return newStr;          
} 

#pragma mark - Image Resize
+ (UIImage *)image:(UIImage *)image drawInRect:(CGRect)rect
{
    UIGraphicsBeginImageContext(rect.size);
    [image drawInRect:rect];
    UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

+ (UIImage *)image:(UIImage *)image fitInSize:(CGSize)size
{
    CGFloat scale;
    CGSize newSize = image.size;
    if (newSize.height != 0) {
        scale = size.height / newSize.height;
        newSize.height *= scale;
        newSize.width *= scale;
    } else {
        return nil;
    }
    if (newSize.width != 0) {
        scale = size.width / newSize.width;
        newSize.height *= scale;
        newSize.width *= scale;
    } else {
        return nil;
    }
    CGFloat x = (size.width - newSize.width) / 2.0f;
    CGFloat y = (size.height - newSize.height) / 2.0f;
    return [Util image:image drawInRect:CGRectMake(x, y, newSize.width, newSize.height)];
}

+ (UIImage *)image:(UIImage *)image centerInSize:(CGSize)size
{
    CGSize newSize = image.size;
    CGFloat x = (size.width - newSize.width)/2.0f;
    CGFloat y = (size.height - newSize.height)/2.0f;
    return [Util image:image drawInRect:CGRectMake(x, y, newSize.width, newSize.height)];
}
+ (UIImage *)image:(UIImage *)image fillInSize:(CGSize)size
{
    CGSize newSize = image.size;
    CGFloat scaleX = 0;
    CGFloat scaleY = 0;
    if (newSize.width != 0) {
        scaleX = size.width/newSize.width;
    } else {
        return nil;
    }
    if (newSize.height != 0) {
        scaleY = size.height/newSize.height;
    } else {
        return nil;
    }
    CGFloat scale = MAX(scaleX, scaleY);
    newSize.width *= scale;
    newSize.height *= scale;
    
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake((size.width-newSize.width)/2.0,
                                 0,
                                 newSize.width,
                                 newSize.height)];
    UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}
+ (UIImage *)image:(UIImage *)image fitToWidth:(CGFloat)width
{
    CGSize newSize = image.size;
    CGFloat scale;
    if (newSize.width != 0) {
        scale = width/newSize.width;
    } else {
        return nil;
    }
    return [Util image:image drawInRect:CGRectMake(0, 0, width, newSize.height*scale)];
}
+ (UIImage *)image:(UIImage *)image fitToHeight:(CGFloat)height
{
    CGSize newSize = image.size;
    CGFloat scale;
    if (newSize.height != 0) {
        scale = height/newSize.height;
    } else {
        return nil;
    }
    return [Util image:image drawInRect:CGRectMake(0, 0, newSize.width*scale, height)];
}

#pragma mark - View to Image
+ (UIImage *)imageByRenderInContextWithView:(UIView *) theView  atFrame:(CGRect)rect
{
    UIGraphicsBeginImageContext(theView.frame.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    UIRectClip(rect);
    [theView.layer renderInContext:context];
    UIImage *temp = UIGraphicsGetImageFromCurrentImageContext();
    
    CGImageRef  imageRef = CGImageCreateWithImageInRect(temp.CGImage, rect);
    UIImage *theImage = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);
    //    UIImageWriteToSavedPhotosAlbum(theImage, nil, nil, nil);
    
    UIGraphicsEndImageContext();
    
    return  theImage;
}

+ (UIImage *)imageByRenderInContextWithView:(UIView *)view
{
    UIGraphicsBeginImageContext(view.bounds.size);
    // Create a filled ellipse
    UIColor *color = [UIColor clearColor];
	[color setFill];
	CGContextFillPath(UIGraphicsGetCurrentContext());
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    //    UIImageWriteToSavedPhotosAlbum(theImage, nil, nil, nil);
    return theImage;
}

+ (void)drawView:(UIView*)view inContext:(CGContextRef)context xOffset:(float)xOffset yOffset:(float)yOffset
{
    CGContextTranslateCTM(context, xOffset, yOffset);
    //    if ([view isKindOfClass:[OHAttributedLabel class]]) {
    //        [(OHAttributedLabel*)view drawTextInRect:view.layer.bounds inContext:context];
    //    } else
    if (![view isKindOfClass:[UIScrollView class]]){
        CGContextSaveGState(context);
        [view.layer renderInContext:context];
        CGContextRestoreGState(context);
    } else {
        for (int subcount = 0; subcount < [view.subviews count]; subcount++) {
            UIView *subview = [view.subviews objectAtIndex:subcount];
            //            if ([subview isKindOfClass:[BanmeView class]]) {
            //                continue;
            //            }
            [self drawView:subview
                 inContext:context
                   xOffset:0+subview.frame.origin.x
                   yOffset:0+subview.frame.origin.y];
        }
    }
    CGContextTranslateCTM(context, -xOffset, -yOffset);
}

+ (UIImage *)imageByDrawInContextWithView:(UIView *)view
{
    CGSize size = view.bounds.size;
    if ([view isKindOfClass:[UIScrollView class]]) {
        size = ((UIScrollView*)view).contentSize;
    }
    return [Util imageByDrawInContextWithView:view inSize:size];
}

+ (UIImage *)imageByDrawInContextWithView:(UIView *)view inSize:(CGSize)size
{
    UIGraphicsBeginImageContext(size);
    // Create a filled ellipse
    UIColor *color = [UIColor clearColor];
	[color setFill];
    //画矩形
    CGContextAddRect(UIGraphicsGetCurrentContext(), view.bounds);
	CGContextFillPath(UIGraphicsGetCurrentContext());
    [self drawView:view inContext:UIGraphicsGetCurrentContext() xOffset:0 yOffset:0];
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    //    UIImageWriteToSavedPhotosAlbum(theImage, nil, nil, nil);
    return theImage;
}

// Return the local MAC addy
// Courtesy of FreeBSD hackers email list
// Accidentally munged during previous update. Fixed thanks to mlamb.

+ (NSString *)getMacAddress
{ 
    int mib[6]; 
    size_t len; 
    char *buf; 
    unsigned char *ptr; 
    struct if_msghdr *ifm; 
    struct sockaddr_dl *sdl; 
    mib[0] = CTL_NET; 
    mib[1] = AF_ROUTE; 
    mib[2] = 0; 
    mib[3] = AF_LINK; 
    mib[4] = NET_RT_IFLIST; 
    if ((mib[5] = if_nametoindex("en0")) == 0) { 
        printf("Error: if_nametoindex error/n"); 
        return NULL; 
    } 
    if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) { 
        printf("Error: sysctl, take 1/n"); 
        return NULL; 
    } 
    if ((buf = malloc(len)) == NULL) { 
        printf("Could not allocate memory. error!/n");
        return NULL; 
    } 
    if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) { 
        printf("Error: sysctl, take 2"); 
        return NULL; 
    } 
    ifm = (struct if_msghdr *)buf; 
    sdl = (struct sockaddr_dl *)(ifm + 1); 
    ptr = (unsigned char *)LLADDR(sdl); 
    NSString *outstring = [NSString stringWithFormat:@"%02x:%02x:%02x:%02x:%02x:%02x", *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)]; 
    free(buf); 
    return [outstring uppercaseString];
}

+ (NSString *)getEncryptMacAddress
{
	StringEncryption *crypto = [[[StringEncryption alloc] init] autorelease];
    NSString * macAdd = [Util getMacAddress];
    if (!macAdd) {
        return nil;
    }
    NSLog(@"Mac address: %@", macAdd);
    CCOptions padding = kCCOptionPKCS7Padding;
    NSString *key = @"wmzhwllsrsfyxhxthbpjklmyljxzlnwh";
    NSData *data = [NSData dataWithBytes:[macAdd UTF8String] 
                                  length:[macAdd lengthOfBytesUsingEncoding:NSUTF8StringEncoding]]; 
    NSData *encryptedData = [crypto encrypt:data 
                                        key:[key dataUsingEncoding:NSUTF8StringEncoding] 
                                    padding:&padding];
    //    return [NSString stringWithCharacters:[encryptedData bytes] length:[encryptedData length]];
    return [GTMBase64 stringByEncodingData:encryptedData];
}
//检查邮箱是否合法
+ (BOOL)validateEmail:(NSString*)email{
    if((0 != [email rangeOfString:@"@"].length) &&
       (0 != [email rangeOfString:@"."].length))
    {
        
        NSCharacterSet* tmpInvalidCharSet = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
        NSMutableCharacterSet* tmpInvalidMutableCharSet = [[tmpInvalidCharSet mutableCopy] autorelease];
        [tmpInvalidMutableCharSet removeCharactersInString:@"_-"];
        
        //使用compare option 来设定比较规则，如
        //NSCaseInsensitiveSearch是不区分大小写
        //NSLiteralSearch 进行完全比较,区分大小写
        //NSNumericSearch 只比较定符串的个数，而不比较字符串的字面值
        NSRange range1 = [email rangeOfString:@"@"
                                      options:NSCaseInsensitiveSearch];
        
        //取得用户名部分
        NSString* userNameString = [email substringToIndex:range1.location];
        NSArray* userNameArray   = [userNameString componentsSeparatedByString:@"."];
        
        for(NSString* string in userNameArray)
        {
            NSRange rangeOfInavlidChars = [string rangeOfCharacterFromSet: tmpInvalidMutableCharSet];
            if(rangeOfInavlidChars.length != 0 || [string isEqualToString:@""])
                return NO;
        }
        
        NSString *domainString = [email substringFromIndex:range1.location+1];
        NSArray *domainArray   = [domainString componentsSeparatedByString:@"."];
        
        for(NSString *string in domainArray)
        {
            NSRange rangeOfInavlidChars=[string rangeOfCharacterFromSet:tmpInvalidMutableCharSet];
            if(rangeOfInavlidChars.length !=0 || [string isEqualToString:@""])
                return NO;
        }
        
        return YES;
    }
    else // no ''@'' or ''.'' present
        return NO;
}
+ (NSString *)sha1:(NSString *)str {
    const char *cstr = [str cStringUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [NSData dataWithBytes:cstr length:str.length];
    
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    
    CC_SHA1(data.bytes, data.length, digest);
    
    NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++) {
        [output appendFormat:@"%02x", digest[i]];
    }
    
    return output;
}

+ (NSString *)md5Hash:(NSString *)str {
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5( cStr, strlen(cStr), result );
    NSString *md5Result = [NSString stringWithFormat:
                           @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                           result[0], result[1], result[2], result[3],
                           result[4], result[5], result[6], result[7],
                           result[8], result[9], result[10], result[11],
                           result[12], result[13], result[14], result[15]
                           ];
    return md5Result;
}

+ (NSInteger)getAlign:(ALIGNTYPE)type
{
    CGFloat ver = [[[UIDevice currentDevice] systemVersion] floatValue];
    switch (type)
    {
        case ALIGNTYPE_LEFT:
        {
            if(ver < 6.0)
            {
                return UITextAlignmentLeft;
            }
            else
            {
                return NSTextAlignmentLeft;
            }
        }break;
        case ALIGNTYPE_CENTER:
        {
            if(ver < 6.0)
            {
                return UITextAlignmentCenter;
            }
            else
            {
                return NSTextAlignmentCenter;
            }
        }break;
        case ALIGNTYPE_RIGHT:
        {
            if(ver < 6.0)
            {
                return UITextAlignmentRight;
            }
            else
            {
                return NSTextAlignmentRight;
            }
        }break;
        default:
        {
            if(ver < 6.0)
            {
                return UITextAlignmentLeft;
            }
            else
            {
                return NSTextAlignmentLeft;
            }
        }
            break;
    }
    
}

#pragma mark - ShowTips
+ (void)showTipsView:(NSString *)tips
{
//    UIWindow *window = [[UIApplication sharedApplication].windows lastObject];
    [self showTipsView:tips atView:[DataEnvironment sharedDataEnvironment].presentingController.view withTextColor:nil backColor:nil];
}

+ (void)showWarningTipsView:(NSString *)tips
{
//    UIWindow *window = [[UIApplication sharedApplication].windows lastObject];
    [self showTipsView:tips atView:[DataEnvironment sharedDataEnvironment].presentingController.view withTextColor:[UIColor yellowColor] backColor:nil];
}

+ (void)showErrorTipsView:(NSString *)tips
{
    UIWindow *window = [[UIApplication sharedApplication].windows lastObject];
    [self showTipsView:tips atView:window withTextColor:COLOR_RGB(255, 53, 36) backColor:nil];
}

+ (void)showTipsView:(NSString *)tips withTextColor:(UIColor *)textColor backColor:(UIColor *)backColor
{
    UIWindow *window = [[UIApplication sharedApplication].windows lastObject];
    [self showTipsView:tips atView:window withTextColor:textColor backColor:backColor];
}

+ (void)showTipsView:(NSString *)tips atView:(UIView *)view
{
    [self showTipsView:tips atView:view withTextColor:nil backColor:nil];
}

+ (void)showTipsView:(NSString *)tips atView:(UIView *)view withTextColor:(UIColor *)textColor backColor:(UIColor *)backColor
{
    CGSize size = CGSizeMake((view.bounds.size.width>320?320:view.bounds.size.width) - 60, 35);
    BMTipsView *tipsview = [[[BMTipsView alloc] initWithTips:tips
                                                     andSize:size
                                                       toDir:PopDirTop
                                                      inView:view
                                                 autoDismiss:YES
                                                       inSec:2.5
                                                   textColor:textColor
                                                   backColor:backColor
                             ] autorelease];
    [tipsview showTips];
}

@end